package cn.bocweb.spinning.view.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bocweb.spinning.R;
import cn.bocweb.spinning.model.Bean.CollectListBean;
import cn.bocweb.spinning.model.Bean.CollectRemoveBean;
import cn.bocweb.spinning.model.Bean.ErrorBean;
import cn.bocweb.spinning.model.Bean.LibListBean;
import cn.bocweb.spinning.model.Bean.SequenceAnswerBean;
import cn.bocweb.spinning.model.Bean.SequenceListBean;
import cn.bocweb.spinning.model.Bean.SequenceSyncBean;
import cn.bocweb.spinning.model.Bean.SequenceSyncForLoginBean;
import cn.bocweb.spinning.model.Bean.SequenceUpdateBean;
import cn.bocweb.spinning.model.Bean.TestCollectBean;
import cn.bocweb.spinning.model.Bean.TrainRandomStartBean;
import cn.bocweb.spinning.model.Bean.UserBean;
import cn.bocweb.spinning.presenter.Imp.UserPresenterImp;
import cn.bocweb.spinning.presenter.UserPresenter;
import cn.bocweb.spinning.util.Constant;
import cn.bocweb.spinning.util.DeviceUtil;
import cn.bocweb.spinning.view.adapter.TestListAdapter;
import cn.bocweb.spinning.view.adapter.TrainAdapter;
import cn.bocweb.spinning.view.common.BaseActivity;
import cn.bocweb.spinning.view.common.ZoomOutPageTransformer;
import cn.bocweb.spinning.view.dialog.ExerciseFinishDialog;
import cn.bocweb.spinning.view.fragment.ExerciseFragment;
import cn.bocweb.spinning.view.fragment.ExerciseFragment;
import cn.bocweb.spinning.view.fragment.MyTestCollectFragment;
import de.greenrobot.event.EventBus;

/**
 * Created by Administrator on 2016/12/10.
 */

public class ExerciseActivity extends BaseActivity implements View.OnClickListener {
    @Bind(R.id.test_btn_test_list)
    LinearLayout testBtnTestList;
    @Bind(R.id.time_limited)
    TextView timeLimited;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.link_exam_fragment)
    ViewPager linkExamFragment;

    int answerWrong = 0, right, wrong, miss;
    boolean collected;
    boolean isRemove = false;

    TextView examPopupRight;
    TextView examPopupWrong;
    TextView examPopupMiss;
    TextView examPopupMore;
    TrainAdapter adapter;
    TestListAdapter testListAdapter;
    PopupWindow popupWindow;
    Map<Integer, Boolean> answerMap;
    RelativeLayout iv;

    @Bind(R.id.train_quiz_num)
    TextView trainQuizNum;
    @Bind(R.id.train_quiz_count)
    TextView traintotal;
    List<SequenceSyncForLoginBean> sequenceSyncForLoginBean;
    List<ExerciseFragment> fragments, fragmentCopy;
    Map<Integer, SequenceAnswerBean> sequences;
    List<SequenceUpdateBean> sequenceUpdateBeans;


    UserPresenter presenter;
    UserBean.DataEntity dataEntity;
    int size, position, exerciseType, popupwindowClickPosition = 0, total, page = 1;
    String userid, libId, json;
    boolean isClientSelect = false, isPopupWindowClick = false, isClickMore = false;
    ExerciseFinishDialog finishDialog;
    boolean isLoadMore;


    @Bind(R.id.train_check_detail)
    LinearLayout trainCheckDetail;
    @Bind(R.id.train_collect)
    LinearLayout trainCollect;

    Map<Integer, String> trainId;
    Map<Integer, String> trainTtype;
    Map<Integer, Integer> trainChoose;
    @Bind(R.id.imageview_collect)
    ImageView imageviewCollect;
    @Bind(R.id.linearLayout_empty)
    LinearLayout linearLayoutEmpty;
    @Bind(R.id.prev_quiz)
    LinearLayout prev_quiz;
    @Bind(R.id.next_quiz)
    LinearLayout next_quiz;
    @Bind(R.id.exer_hint)
    TextView exer_hint;
    int ExerciseType;
    int delectPosition;
    int backToSequencePage = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_train);
        ButterKnife.bind(this);

        trainId = new HashMap<>();
        trainTtype = new HashMap<>();
        trainChoose = new HashMap<>();
        sequences = new HashMap<>();

        dataEntity = new UserBean.DataEntity();
        dataEntity.readInfoFromLocal(this);
        userid = dataEntity.getUserid();
        fragmentCopy = new ArrayList<>();
        fragments = new ArrayList<>();
        sequenceUpdateBeans = new ArrayList<>();
        finishDialog = new ExerciseFinishDialog(this);
        UserBean.DataEntity user = new UserBean.DataEntity();
        user.readInfoFromLocal(this);
        userid = user.getUserid();
        LibListBean.DataEntity lib = new LibListBean.DataEntity();
        lib.readLibListIntoLocal(this);
        libId = lib.getId();

        EventBus.getDefault().register(this);
        presenter = new UserPresenterImp();
        initViewPager();

        initIntent();
        initToolbar();
        initPopupWindow();
        initClickBtn();
//        initModel();
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }


    @Override
    protected void onRestart() {
        super.onRestart();
        if (userid == null || userid.isEmpty()) {
            UserBean.DataEntity dataEntity = new UserBean.DataEntity();
            dataEntity.readInfoFromLocal(this);
            userid = dataEntity.getUserid();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case Constant.TRAIN_TO_LOGIN: {
                UserBean.DataEntity dataEntity = new UserBean.DataEntity();
                dataEntity.readInfoFromLocal(this);
                userid = dataEntity.getUserid();
                break;
            }
            case Constant.SEQUENCE_TEST_SYNC: {
                UserBean.DataEntity dataEntity = new UserBean.DataEntity();
                dataEntity.readInfoFromLocal(this);
                userid = dataEntity.getUserid();
                if (userid != null && !userid.isEmpty()) {
                    presenter.sequenceSync(libId, userid, json);
                }
                break;
            }
            case Constant.SEQUENCE_TEST_COLLECT: {
                UserBean.DataEntity dataEntity = new UserBean.DataEntity();
                dataEntity.readInfoFromLocal(this);
                userid = dataEntity.getUserid();
                backToSequencePage = linkExamFragment.getCurrentItem();
                isClientSelect = true;
                fragments.clear();
                adapter.notifyDataSetChanged();
                presenter.sequenceList(libId, userid, "49", 1);
                break;
            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }


    private void initIntent() {

        Intent intent = getIntent();
        exerciseType = intent.getIntExtra(Constant.TRAIN, 0);
        showLoading();
        switch (exerciseType) {
//            case Constant.TRAIN_RANDOM: {
//                presenter.trainRandomStart("1", libId, userid, "1");
//                break;
//            }
            case Constant.TRAIN_ERROR: {
                presenter.errorTrainStart("1", libId, userid);
                break;
            }
//            case Constant.TRAIN_DIFF: {
//                presenter.hardTrainStart("1", libId, userid);
//                break;
//            }
            case Constant.SEQUENCE: {
                presenter.sequenceList(libId, userid, "49", page);
                showLoading();
                break;
            }
            case Constant.COLLECT: {
                presenter.collectList(libId, userid, "50", page);
                imageviewCollect.setImageResource(R.mipmap.exam_del);
                timeLimited.setText("取消收藏");
                break;
            }
        }
    }

    private void initToolbar() {
        toolbar.setNavigationIcon(R.mipmap.btn_exit);

        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                finishDialog.show();
                finishDialog.setOnClickListener(new ExerciseFinishDialog.OnClickListener() {
                    @Override
                    public void click(View v) {
                        dialog.dismiss();
                        if (exerciseType == Constant.SEQUENCE) {
                            setResult(Constant.SEQUENCE_BACK_MAIN);
                        }
                        finish();
                    }
                });
            }
        });
    }

    /**
     * 获得题目列表
     */
    public void onEventMainThread(SequenceListBean bean) {
        if (bean.getReturn_code() == 0) {
            if (!isClickMore) {
                for (int i = 0; i < bean.getData().size(); i++) {
                    if (bean.getData().get(i).getDetail() != null) {
                        switch (bean.getData().get(i).getDetail().getIsright()) {
                            case "0": {
                                answerMap.put(i, false);
                                wrong++;
                                break;
                            }
                            case "1": {
                                answerMap.put(i, true);
                                right++;
                                break;
                            }
                        }
                    }
                }
                total = bean.getData().size();

                if (bean.getLast() != null && !bean.getLast().isEmpty()) {
                    int last = Integer.parseInt(bean.getLast());
                    int firstLoadCount;
                    if (last > 49) {
                        firstLoadCount = 49 * (last / 49 + 1);
                    } else {
                        firstLoadCount = 49;
                    }
                    for (int i = 0; i < firstLoadCount; i++) {
                        ExerciseFragment fragment = new ExerciseFragment(i, Constant.SEQUENCE, userid, libId, total);
                        fragment.setUserid(userid);
                        fragmentCopy.add(fragment);
                    }
                } else {
                    for (int i = 0; i < bean.getData().size(); i++) {
                        fragmentCopy.add(new ExerciseFragment(i, Constant.SEQUENCE, userid, libId, total));
                    }
                }

                fragments.addAll(fragmentCopy);
                adapter.notifyDataSetChanged();
                miss = bean.getTotal();
                examPopupMiss.setText(String.valueOf(bean.getTotal() - bean.getRightCount() - bean.getErrorCount()));
                examPopupRight.setText(String.valueOf(bean.getRightCount()));
                examPopupWrong.setText(String.valueOf(bean.getErrorCount()));
                trainQuizNum.setText(String.valueOf(linkExamFragment.getCurrentItem() + 1));
                testListAdapter.setSize(bean.getData().size());
                testListAdapter.notifyDataSetChanged();
                traintotal.setText(String.valueOf(bean.getTotal()));

                if (!isClientSelect) {
                    if (bean.getLast() != null && !bean.getLast().isEmpty()) {
                        if (Integer.parseInt(bean.getLast()) != 0) {
                            linkExamFragment.setCurrentItem(Integer.parseInt(bean.getLast()));
                        } else {
                            linkExamFragment.setCurrentItem(1);
                            linkExamFragment.setCurrentItem(0);
                        }
                    } else {
                        linkExamFragment.setCurrentItem(1);
                        linkExamFragment.setCurrentItem(0);
                    }
                } else {
                    linkExamFragment.setCurrentItem(backToSequencePage);
                }
            } else {
                for (int i = 0; i < bean.getData().size(); i++) {
                    if (bean.getData().get(i).getDetail() != null) {
                        switch (bean.getData().get(i).getDetail().getIsright()) {
                            case "0": {
                                answerMap.put(total + i, false);
                                wrong++;
                                break;
                            }
                            case "1": {
                                answerMap.put(total + i, true);
                                right++;
                                break;
                            }
                        }
                    }
                }

                examPopupMiss.setText(String.valueOf(bean.getTotal() - bean.getRightCount() - bean.getErrorCount()));
                examPopupRight.setText(String.valueOf(bean.getRightCount()));
                examPopupWrong.setText(String.valueOf(bean.getErrorCount()));

                for (int i = 0; i < bean.getData().size(); i++) {
                    if (fragments.size() < (i + total + 1)) {
                        fragments.add(new ExerciseFragment(i + total, Constant.SEQUENCE, userid, libId, i + total));
                        DeviceUtil.Log("load more = " + (total + i));
                    }
                }
                total += bean.getData().size();
                examPopupMiss.setText(String.valueOf(miss + bean.getData().size()));
                adapter.notifyDataSetChanged();
                testListAdapter.setSize(total);
                testListAdapter.notifyDataSetChanged();

                if (isLoadMore) {
                    fragments.get(linkExamFragment.getCurrentItem()).setVisible(true);
                    isLoadMore = false;
                }
            }
        } else if (bean.getReturn_code() == -203) {
            examPopupMore.setText("已经是最后一页");
        }
        hideLoading();
    }

    @Override
    public void onBackPressed() {
        finishDialog.show();
        finishDialog.setOnClickListener(new ExerciseFinishDialog.OnClickListener() {
            @Override
            public void click(View v) {
                dialog.dismiss();
                finish();
            }
        });
    }

    private void initPopupWindow() {

        answerMap = new HashMap<>();
        View view = LayoutInflater.from(this).inflate(R.layout.window_test_list, null);
        GridView gridView_testList = (GridView) view.findViewById(R.id.test_list);
        iv = (RelativeLayout) view.findViewById(R.id.btn_hide);

        testListAdapter = new TestListAdapter(this, size, answerMap, false);

        examPopupRight = (TextView) view.findViewById(R.id.exam_popup_right);
        examPopupWrong = (TextView) view.findViewById(R.id.exam_popup_wrong);
        examPopupMiss = (TextView) view.findViewById(R.id.exam_popup_miss);
        examPopupMore = (TextView) view.findViewById(R.id.exam_popup_more);
        examPopupMore.setVisibility(View.VISIBLE);
        examPopupMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (exerciseType) {
                    case Constant.SEQUENCE:
                        if (TextUtils.isEmpty(userid)) {
                            AlertDialog.Builder builder = new AlertDialog.Builder(ExerciseActivity.this);
                            builder.setTitle("提示");
                            builder.setMessage("是否登录(登录后保存题目)");
                            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    for (int i = 0; i < fragments.size(); i++) {
                                        if (answerMap.containsKey(i)) {
                                            sequenceSyncForLoginBean.add(fragments.get(i).getSequenceSyncForLoginBean());
                                        }
                                    }

                                    Gson gson = new Gson();
                                    json = gson.toJson(sequenceSyncForLoginBean);

                                    Intent intent = new Intent(ExerciseActivity.this, LoginAcivity.class);
                                    intent.putExtra(Constant.ACTIVITY_TO_LOGIN, Constant.SEQUENCE_TEST_SYNC);
                                    startActivityForResult(intent, Constant.SEQUENCE_TEST_SYNC);
                                }
                            });
                            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    finish();
                                }
                            });
                            builder.show();
                        } else {
                            isClickMore = true;
                            page++;
                            presenter.sequenceList(libId, userid, "49", page);
                        }
                        break;
                    case Constant.TRAIN_ERROR:
                        break;
                    case Constant.COLLECT:
                        page++;
                        presenter.collectList(libId, userid, "50", page);
                        break;
                }
            }
        });

        gridView_testList.setAdapter(testListAdapter);


        int screenHeightPx = DeviceUtil.getScreenHeight(this);
        int navigationHeight = DeviceUtil.getStatusBarHeight(this);
        int toolbarHeight = DeviceUtil.getViewHeight(toolbar);

        /**
         * 安卓5.0以下有个问题就是用gridview的onItemClickListener监听不到item的监听事件.真他妈的奇怪
         */
        testListAdapter.setOnItemClickListener(new TestListAdapter.OnItemClickListener() {
            @Override
            public void click(int position) {
                isPopupWindowClick = true;
                popupwindowClickPosition = position;
                linkExamFragment.setCurrentItem(position);
                popupWindow.dismiss();
            }
        });

        popupWindow = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT, screenHeightPx - navigationHeight - toolbarHeight);
        popupWindow.setAnimationStyle(R.style.test_list);
    }

    private void initClickBtn() {
        testBtnTestList.setOnClickListener(this);
        iv.setOnClickListener(this);
        trainCheckDetail.setOnClickListener(this);
        trainCollect.setOnClickListener(this);
        prev_quiz.setOnClickListener(this);
        next_quiz.setOnClickListener(this);
    }

    private void initViewPager() {
        adapter = new TrainAdapter(getSupportFragmentManager(), fragments);
        linkExamFragment.setAdapter(adapter);
        linkExamFragment.setPageTransformer(true, new ZoomOutPageTransformer());
        linkExamFragment.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                trainQuizNum.setText(String.valueOf(position + 1));
                switch (exerciseType) {
                    case Constant.TRAIN_ERROR: {

                        break;
                    }
                    case Constant.SEQUENCE: {

                        if ((position + 1) % 49 == 0 && fragments.size() == (position + 1)) {
                            loadMore();
                            DeviceUtil.MyToast(ExerciseActivity.this, "正在获取下一批题目");
                        }
                        break;
                    }
                    case Constant.COLLECT: {

                        break;
                    }
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    public void isCollect(boolean isCollect) {
        collected = isCollect;
        if (isCollect) {
            imageviewCollect.setImageResource(R.mipmap.collected);
        } else {
            imageviewCollect.setImageResource(R.mipmap.train_collect);
        }
    }

    private void popToast() {
        switch (exerciseType) {
            case 1:
                DeviceUtil.MyToast(ExerciseActivity.this, "当前题库无题目");
                exer_hint.setText("当前题库无题目");
                linearLayoutEmpty.setVisibility(View.VISIBLE);
                linkExamFragment.setVisibility(View.GONE);
                break;
            case 2:
                DeviceUtil.MyToast(ExerciseActivity.this, "当前无错题");
                exer_hint.setText("当前无错题");
                linearLayoutEmpty.setVisibility(View.VISIBLE);
                linkExamFragment.setVisibility(View.GONE);
                break;
            case 3:
                DeviceUtil.MyToast(ExerciseActivity.this, "您还没有收藏当前题库的题目");
                exer_hint.setText("您没有该题库的收藏题目");
                linearLayoutEmpty.setVisibility(View.VISIBLE);
                linkExamFragment.setVisibility(View.GONE);
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.test_btn_test_list: {
                if (fragments.isEmpty()) {
                    //去掉，改为弹出
                    popToast();
                    break;
                }
                testListAdapter.notifyDataSetChanged();
                popupWindow.showAtLocation(linkExamFragment, Gravity.BOTTOM, 0, 0);
                break;
            }
            case R.id.btn_hide: {
                popupWindow.dismiss();
                break;
            }
            case R.id.train_check_detail: {
                if (fragments.isEmpty()) {
                    popToast();
                    break;
                }
                if (fragments.size() > 0) {
                    fragments.get(linkExamFragment.getCurrentItem()).showDetail();
                }
                break;
            }
            case R.id.train_collect: {
                if (fragments.isEmpty()) {
                    break;
                }
                switch (exerciseType) {
                    case Constant.TRAIN_ERROR: {
                        if (userid != null && !userid.isEmpty()) {
                            String isright;
                            if (answerMap.containsKey(linkExamFragment.getCurrentItem())) {
                                isright = (answerMap.get(linkExamFragment.getCurrentItem())) ? "1" : "0";
                            } else {
                                isright = "2";
                            }

                            String choose;
                            if (trainChoose.containsKey(linkExamFragment.getCurrentItem())) {
                                choose = String.valueOf(trainChoose.get(linkExamFragment.getCurrentItem()));
                            } else {
                                choose = "0";
                            }
                            int positions = linkExamFragment.getCurrentItem();
                            String isright1 = fragments.get(positions).isRight() ? "1" : "0";
                            if (collected) {
                                presenter.collectRemove(libId, userid, "2", fragments.get(positions).getTid(), fragments.get(positions).getTtype());
                            } else {
                                presenter.testCollect(fragments.get(positions).getTId(), fragments.get(positions).getTtype(), libId, userid, isright1, fragments.get(positions).getResult());
                            }
                            break;
                        } else {
                            Intent intent = new Intent(this, LoginAcivity.class);
                            intent.putExtra(Constant.ACTIVITY_TO_LOGIN, Constant.TRAIN_TO_LOGIN);
                            startActivity(intent);
                        }
                        break;
                    }
                    case Constant.SEQUENCE: {
                        if (userid == null || userid.isEmpty()) {
                            Intent intent = new Intent(this, LoginAcivity.class);
                            intent.putExtra(Constant.ACTIVITY_TO_LOGIN, Constant.SEQUENCE_TEST_COLLECT);
                            startActivityForResult(intent, Constant.SEQUENCE_TEST_COLLECT);
                        } else {
                            if (collected) {
                                presenter.collectRemove(libId, userid, "2", fragments.get(linkExamFragment.getCurrentItem()).getTid(), fragments.get(linkExamFragment.getCurrentItem()).getTtype());
                            } else {
                                fragments.get(linkExamFragment.getCurrentItem()).setCollect(linkExamFragment.getCurrentItem());
                            }
                        }
                        break;
                    }
                    case Constant.COLLECT: {
                        DeviceUtil.Log("id = " + fragments.get(linkExamFragment.getCurrentItem()).getId() + " ttype = " + fragments.get(linkExamFragment.getCurrentItem()).getTtype());
                        presenter.collectRemove(libId, userid, "2", fragments.get(linkExamFragment.getCurrentItem()).getTid(), fragments.get(linkExamFragment.getCurrentItem()).getTtype());
                        delectPosition = linkExamFragment.getCurrentItem();
                        break;
                    }

                }
            }
            case R.id.prev_quiz: {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (linkExamFragment.getCurrentItem() != 0) {
                            linkExamFragment.setCurrentItem(linkExamFragment.getCurrentItem() - 1);
                        } else {
                            DeviceUtil.MyToast(ExerciseActivity.this, "已是第一题");
                        }
                    }
                });
                break;
            }
            case R.id.next_quiz: {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        switch (exerciseType) {
                            case Constant.SEQUENCE: {
                                if (exerciseType == Constant.SEQUENCE) {
                                    if ((position + 1) % 49 == 0 && fragments.size() == (position + 1)) {
                                        loadMore();
                                        DeviceUtil.MyToast(ExerciseActivity.this, "正在获取下一批题目");
                                    } else {
                                        trainQuizNum.setText(String.valueOf(position + 1));
                                        linkExamFragment.setCurrentItem(linkExamFragment.getCurrentItem() + 1);
                                    }
                                } else {
                                    trainQuizNum.setText(String.valueOf(position + 1));
                                    linkExamFragment.setCurrentItem(linkExamFragment.getCurrentItem() + 1);
                                }
                                break;
                            }
                            case Constant.COLLECT: {
                                if ((position + 1) < total) {
                                    trainQuizNum.setText(String.valueOf(position + 1));
                                    linkExamFragment.setCurrentItem(linkExamFragment.getCurrentItem() + 1);
                                } else {
                                    DeviceUtil.MyToast(ExerciseActivity.this, "已经是最后一题");
                                }
                                break;
                            }
                            case Constant.TRAIN_ERROR: {
                                if ((position + 1) < total) {
                                    trainQuizNum.setText(String.valueOf(position + 1));
                                    linkExamFragment.setCurrentItem(linkExamFragment.getCurrentItem() + 1);
                                } else {
                                    DeviceUtil.MyToast(ExerciseActivity.this, "已经是最后一题");
                                }
                                break;
                            }

                        }

//                        if (linkExamFragment.getCurrentItem() != (dataEntities.size() - 1)) {
//
//                            if (fragments.get(pos).initSelectResult()) {
//                                linkExamFragment.setCurrentItem(linkExamFragment.getCurrentItem() + 1);
//                                Log.e("====pos",""+pos);
//                            }else {
//
//                                DeviceUtil.MyToast(getApplicationContext(), "您还未选择答案");
//                            }
//
//                        }else {
//                            fragments.get(pos).initSelectResult();
//                        }
                    }
                });
            }
        }
    }

    public void addQuizCorrect(String ttype, String tid, String choose, boolean isCurrent, int position) {

        SequenceUpdateBean bean = new SequenceUpdateBean();
        bean.setTtype(ttype);
        bean.setTid(tid);
        bean.setChoose(choose);
        bean.setCount(String.valueOf(position + 1));
        if (isCurrent) {
            bean.setIsright("1");
        } else {
            bean.setIsright("0");
        }
        sequenceUpdateBeans.add(bean);

        answerMap.put(position, isCurrent);
        if (!isCurrent) {
            wrong = wrong + 1;
            examPopupWrong.setText(String.valueOf(wrong));
            answerWrong++;
        } else {
            right = right + 1;
            examPopupRight.setText(String.valueOf(right));
        }
        miss -= 1;
        examPopupMiss.setText(String.valueOf(miss));
    }

    public void addQuizCorrect(int position, boolean isCurrent) {


        answerMap.put(position, isCurrent);
        if (!isCurrent) {
            wrong = wrong + 1;
            examPopupWrong.setText(String.valueOf(wrong));
            answerWrong++;
        } else {
            right = right + 1;
            examPopupRight.setText(String.valueOf(right));
        }
        miss -= 1;
        examPopupMiss.setText(String.valueOf(miss));
        answerMap.put(position, isCurrent);
        if (!isCurrent) {
            wrong = wrong + 1;
            examPopupWrong.setText(String.valueOf(wrong));
            answerWrong++;
        } else {
            right = right + 1;
            examPopupRight.setText(String.valueOf(right));
        }

        examPopupMiss.setText(String.valueOf(total - wrong - right));
    }

    public void addQuizChoose(int position, int choose) {
        trainChoose.put(position, choose);
    }

    public void onEventMainThread(TrainRandomStartBean bean) {
        if (bean.getReturn_code() == 0) {
            total = bean.getTotal();
            trainId.put(linkExamFragment.getCurrentItem(), bean.getData().getId());
            trainTtype.put(linkExamFragment.getCurrentItem(), bean.getData().getTtype());
            for (int i = 0; i < (bean.getTotal()); i++) {
                ExerciseFragment ExerciseFragment = new ExerciseFragment(i, exerciseType, userid, libId, total);
                fragments.add(ExerciseFragment);
            }

            trainQuizNum.setText("1");
            traintotal.setText(" " + bean.getTotal());
            adapter.notifyDataSetChanged();
            testListAdapter.setSize(bean.getTotal());
            testListAdapter.notifyDataSetChanged();
            examPopupMiss.setText(String.valueOf(total));
        } else if (bean.getReturn_code() == -206) {
//            if (exerciseType == 1) {
//                presenter.trainRandomStart("1", libId, userid, "1");
//            }
        } else if (bean.getReturn_code() == -205) {
            linearLayoutEmpty.setVisibility(View.VISIBLE);
            linkExamFragment.setVisibility(View.GONE);
        } else {
            DeviceUtil.MyToast(this, bean.getMsg());
            hideLoading();
            finish();
        }
        hideLoading();
    }

    public void addQuizDetail(SequenceAnswerBean bean, int position) {
        if (position == linkExamFragment.getCurrentItem()) {
            sequences.put(linkExamFragment.getCurrentItem(), bean);
        }
    }

    public void onEventMainThread(CollectRemoveBean bean) {
        switch (exerciseType) {
            case Constant.TRAIN_ERROR: {
                if (bean.getReturn_code() == 0) {
                    imageviewCollect.setImageResource(R.mipmap.train_collect);
                    collected = false;
                } else {
                    DeviceUtil.MyToast(this, bean.getMsg());
                }
                break;
            }
            case Constant.SEQUENCE: {
                if (bean.getReturn_code() == 0) {
                    imageviewCollect.setImageResource(R.mipmap.train_collect);
                    collected = false;
                } else {
                    DeviceUtil.MyToast(this, bean.getMsg());
                }
            }
            case Constant.COLLECT: {
                if (bean.getReturn_code() == 0) {
                    total--;
                    traintotal.setText(String.valueOf(total));
                    fragments.remove(delectPosition);
                    if (linkExamFragment.getCurrentItem() == 0) {
                        linkExamFragment.setCurrentItem(0);
                    } else {
                        for (int i = linkExamFragment.getCurrentItem() + 1; i < fragments.size(); i++) {
                            fragments.get(i).setPosition(i - 1);
                        }

                    }
                    adapter.notifyDataSetChanged();
                    linkExamFragment.setCurrentItem(delectPosition);
                    isRemove = true;
                    answerMap.remove(delectPosition);
                    testListAdapter.setSize(total);
                    testListAdapter.notifyDataSetChanged();
                    trainQuizNum.setText(String.valueOf(linkExamFragment.getCurrentItem() + 1));

                    if (fragments.size() == 0) {
                        linkExamFragment.setVisibility(View.GONE);
                        linearLayoutEmpty.setVisibility(View.VISIBLE);
                        exer_hint.setText("您还没有该题库的收藏题目");
                        trainQuizNum.setText("0");
                    }
                } else {
                    DeviceUtil.MyToast(this, bean.getMsg());
                }
            }
        }
    }

    public void onEventMainThread(CollectListBean bean) {

        if (bean.getReturn_code() == 0) {
            linkExamFragment.setVisibility(View.VISIBLE);
            linearLayoutEmpty.setVisibility(View.GONE);
            if (!isRemove) {
                total = bean.getTotal();
                for (int i = 0; i < bean.getTotal(); i++) {
                    fragments.add(new ExerciseFragment(i, Constant.COLLECT, userid, libId, total));
//                    switch (Integer.parseInt(bean.getData().get(i).getIsright())) {
//                        case 0: {
//                            answerMap.put(i, false);
//                            break;
//                        }
//                        case 1: {
//                            answerMap.put(i, true);
//                            break;
//                        }
//                        case 2: {
//                            break;
//                        }
//                    }
                }
                trainQuizNum.setText(String.valueOf(linkExamFragment.getCurrentItem() + 1));
                adapter.notifyDataSetChanged();
                traintotal.setText(String.valueOf(total));
                testListAdapter.setSize(bean.getTotal());
                testListAdapter.notifyDataSetChanged();
            } else {
                fragments.clear();
                adapter.notifyDataSetChanged();
                for (int i = 0; i < bean.getTotal(); i++) {
                    fragments.add(new ExerciseFragment(i, Constant.COLLECT, userid, libId, total));
//                    switch (Integer.parseInt(bean.getData().get(i).getIsright())) {
//                        case 0: {
//                            answerMap.put(i, false);
//                            break;
//                        }
//                        case 1: {
//                            answerMap.put(i, true);
//                            break;
//                        }
//                        case 2: {
//                            break;
//                        }
//                    }
                }
                adapter.notifyDataSetChanged();
                traintotal.setText(String.valueOf(total));
                testListAdapter.setSize(bean.getTotal());
                testListAdapter.notifyDataSetChanged();
            }
        } else if (bean.getReturn_code() == -204) {
            exer_hint.setText("您没有该题库的收藏题目");
            linkExamFragment.setVisibility(View.GONE);
            linearLayoutEmpty.setVisibility(View.VISIBLE);
        } else {
            DeviceUtil.MyToast(this, bean.getMsg());
        }
        hideLoading();
    }

    /**
     * 判断用户是不是做完了所有的题目
     *
     * @return true 做完了, false 没做完
     */
    public boolean isAllAnswer() {
        return answerMap.size() == total;
    }

    public void onEventMainThread(TestCollectBean bean) {
        if (bean.getReturn_code() == 0) {
            isCollect(true);
        }
        DeviceUtil.MyToast(this, bean.getMsg());
        hideLoading();
    }

    public void onEventMainThread(ErrorBean bean) {
        hideLoading();
        DeviceUtil.MyToast(this, bean.getErrorMsg());
    }

    public void onEventMainThread(SequenceSyncBean bean) {
        if (bean.getReturn_code() == 0) {
            DeviceUtil.MyToast(this, bean.getMsg());
            isClickMore = true;
            page++;
            presenter.sequenceList(libId, userid, "49", page);
        } else {
            DeviceUtil.Log("bean = " + bean.getReturn_code() + " msg = " + bean.getMsg());
        }
    }

    public void selectRightAnswer(final int page) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                linkExamFragment.setCurrentItem(page);
            }
        });
    }

    public void loadMore() {
        isClickMore = true;
        isLoadMore = true;
        page++;
        presenter.sequenceList(libId, userid, "49", page);
    }

}
